Skip to main content

πŸ’Ύ Bit Manipulation

Bit tricks turn O(n)O(n) scans into single CPU instructions. The arsenal is small but the payoff is huge β€” memorize the idioms below and they will appear everywhere.

This category contains 14 problems. Use the patterns below to recognize what's being asked, then jump to the problem list at the bottom.


🧠 Key Patterns​

  • XOR for "find unique" β€” a ^ a = 0, a ^ 0 = a. Single Number family.
  • Clear lowest set bit β€” n & (n - 1) β€” count set bits, power-of-two check.
  • Bitmask DP β€” State = subset of items, often up to ~20 elements.
  • Bit-by-bit reconstruction β€” Sum each bit position mod 3, mod k, etc.
  • Built-ins β€” BitOperations.PopCount, LeadingZeroCount, TrailingZeroCount (C#).

⚠️ Common Pitfalls​

  • Signed vs unsigned shifts. >> on negative int keeps the sign bit. Use (uint).
  • Operator precedence: (x & 1) == 0 needs the parens.

πŸ“š Study Resources​

πŸ“Ί Videos​

πŸ“– Books​

  • Hacker's Delight β€” Henry S. Warren β€” The definitive bit-twiddling reference
  • Competitive Programming Handbook β€” Laaksonen β€” Ch. 10

🌐 Articles & References​


πŸ’» All Bit Manipulation Problems​